package code._15network.tcp.v4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class server4 {
    public static void main(String[] args) throws IOException {
        //创建serverSocket；
        ServerSocket serverSocket = new ServerSocket(9999);
        //连接、accept、获取socket
        Socket socket = serverSocket.accept();
        //获取socket的输入流InputStream
        InputStream inputStream = socket.getInputStream();
        //转换为字符流InputStreamReader
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        //获取文件类容、并保存
        char[] chars = new char[1024];
        int readCount;
        boolean flag=true;
        //创建输出字符流OutputStreamWriter
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("fileTest\\b.txt"));
        while (flag){
            while ((readCount=inputStreamReader.read(chars))!=-1){
                //将读取的类容保存到文件
                outputStreamWriter.write(chars,0,readCount);
                //刷新缓冲区
                outputStreamWriter.flush();
            }
            flag=false;
        }
        //通知client保存完成
        //获取socket输出流OutputStream
        OutputStream outputStream = socket.getOutputStream();
        OutputStreamWriter outWriterSocket = new OutputStreamWriter(outputStream);
        outWriterSocket.write("文件保存完成");
        //释放资源
        outWriterSocket.close();
        socket.close();
        serverSocket.close();
        inputStreamReader.close();
    }
}
